<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>{{.title}}</title>
    <link href="/static/css/app.css" rel="stylesheet" />
  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-info">
      <div class="container-fluid">
        <span class="navbar-brand">📁 企业文档存储系统</span>
        <div class="navbar-nav ms-auto">
          <span class="nav-link">欢迎, {{.user.Username}}</span>
          <a class="nav-link" href="/logout">退出</a>
        </div>
      </div>
    </nav>

    <div class="container-fluid mt-4">
      {{if .error}}
      <div class="alert alert-danger" role="alert">{{.error}}</div>
      {{end}}

      <div class="row">
        <!-- 侧边栏 - 容器列表 -->
        <div class="col-md-3">
          <div class="card">
            <div class="card-header">
              <h6 class="mb-0">存储容器</h6>
            </div>
            <div class="list-group list-group-flush">
              {{range .containers}}
              <a
                href="/webdrive?container={{.Name}}"
                class="list-group-item list-group-item-action {{if eq .Name $.current_container}}active{{end}}"
              >
                <div class="d-flex w-100 justify-content-between">
                  <h6 class="mb-1">{{.Name}}</h6>
                  <small>{{.Count}} 文件</small>
                </div>
              </a>
              {{else}}
              <div class="list-group-item text-muted">暂无可访问容器</div>
              {{end}}
            </div>
          </div>
        </div>

        <!-- 主内容区 - 文件列表 -->
        <div class="col-md-9">
          {{if .current_container}}
          <div class="card">
            <div
              class="card-header d-flex justify-content-between align-items-center"
            >
              <h5 class="mb-0">📂 {{.current_container}}</h5>
              {{if .upload_enabled}}
              <button
                class="btn btn-primary btn-sm"
                data-bs-toggle="modal"
                data-bs-target="#uploadModal"
              >
                📤 上传文件
              </button>
              {{end}}
            </div>
            <div class="card-body">
              {{if .objects}}
              <div class="table-responsive">
                <table class="table table-hover">
                  <thead>
                    <tr>
                      <th>文件名</th>
                      <th>大小</th>
                      <th>类型</th>
                      <th>修改时间</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    {{range .objects}}
                    <tr>
                      <td>{{.Name}}</td>
                      <td>{{formatFileSize .Bytes}}</td>
                      <td>
                        <small class="text-muted">{{.ContentType}}</small>
                      </td>
                      <td>{{.LastModified.Format "2006-01-02 15:04"}}</td>
                      <td>
                        <div class="btn-group btn-group-sm">
                          <a
                            href="/download/{{$.current_container}}/{{.Name}}"
                            class="btn btn-outline-primary"
                            title="下载"
                          >
                            📥
                          </a>
                          <button
                            class="btn btn-outline-info"
                            onclick="getFileInfo('{{$.current_container}}', '{{.Name}}')"
                            title="属性"
                          >
                            ℹ️
                          </button>
                          {{if $.delete_enabled}}
                          <button
                            class="btn btn-outline-danger"
                            onclick="deleteFile('{{$.current_container}}', '{{.Name}}')"
                            title="删除"
                          >
                            🗑️
                          </button>
                          {{end}}
                        </div>
                      </td>
                    </tr>
                    {{end}}
                  </tbody>
                </table>
              </div>
              {{else}}
              <div class="text-center text-muted py-5">
                <h5>📭 容器为空</h5>
                <p>这个容器中还没有文件</p>
                {{if .upload_enabled}}
                <button
                  class="btn btn-primary"
                  data-bs-toggle="modal"
                  data-bs-target="#uploadModal"
                >
                  上传第一个文件
                </button>
                {{end}}
              </div>
              {{end}}
            </div>
          </div>
          {{else}}
          <div class="card">
            <div class="card-body text-center">
              <h5 class="text-muted">请选择一个容器开始管理文件</h5>
              <p class="text-muted">从左侧列表中选择要访问的存储容器</p>
            </div>
          </div>
          {{end}}
        </div>
      </div>
    </div>

    <!-- 上传文件模态框 -->
    {{if .upload_enabled}}
    <div class="modal fade" id="uploadModal" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">上传文件到 {{.current_container}}</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
            ></button>
          </div>
          <div class="modal-body">
            <form id="uploadForm" enctype="multipart/form-data">
              <input
                type="hidden"
                name="container"
                value="{{.current_container}}"
              />
              <div class="mb-3">
                <label for="file" class="form-label">选择文件</label>
                <input
                  type="file"
                  class="form-control"
                  id="file"
                  name="file"
                  required
                />
                <div class="form-text">
                  支持格式: PDF, Office文档, 图片, 压缩包等<br />
                  最大大小: 100MB
                </div>
              </div>
              <div class="mb-3">
                <div class="progress d-none" id="uploadProgress">
                  <div
                    class="progress-bar"
                    role="progressbar"
                    style="width: 0%"
                  ></div>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              取消
            </button>
            <button
              type="button"
              class="btn btn-primary"
              onclick="uploadFile()"
            >
              上传
            </button>
          </div>
        </div>
      </div>
    </div>
    {{end}}

    <!-- 文件信息模态框 -->
    <div class="modal fade" id="infoModal" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">文件属性</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
            ></button>
          </div>
          <div class="modal-body" id="fileInfoContent">
            <!-- 动态内容 -->
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              关闭
            </button>
          </div>
        </div>
      </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
      // 上传文件
      function uploadFile() {
        const form = document.getElementById("uploadForm");
        const formData = new FormData(form);
        const progressBar = document.getElementById("uploadProgress");

        progressBar.classList.remove("d-none");

        fetch("/upload", {
          method: "POST",
          body: formData,
        })
          .then((response) => response.json())
          .then((data) => {
            if (data.error) {
              alert("上传失败: " + data.error);
            } else {
              alert("文件上传成功！");
              location.reload();
            }
          })
          .catch((error) => {
            alert("上传失败: " + error.message);
          })
          .finally(() => {
            progressBar.classList.add("d-none");
            document
              .getElementById("uploadModal")
              .querySelector(".btn-close")
              .click();
          });
      }

      // 获取文件信息
      function getFileInfo(container, objectName) {
        fetch(`/info/${container}/${objectName}`)
          .then((response) => response.json())
          .then((data) => {
            if (data.error) {
              alert("获取文件信息失败: " + data.error);
              return;
            }

            const content = `
                    <dl class="row">
                        <dt class="col-sm-4">文件名:</dt>
                        <dd class="col-sm-8"><code>${data.name}</code></dd>
                        
                        <dt class="col-sm-4">容器:</dt>
                        <dd class="col-sm-8"><code>${data.container}</code></dd>
                        
                        <dt class="col-sm-4">文件类型:</dt>
                        <dd class="col-sm-8">${
                          data.metadata["content-type"]
                        }</dd>
                        
                        <dt class="col-sm-4">文件大小:</dt>
                        <dd class="col-sm-8">${formatBytes(
                          parseInt(data.metadata["content-length"])
                        )}</dd>
                        
                        <dt class="col-sm-4">修改时间:</dt>
                        <dd class="col-sm-8">${
                          data.metadata["last-modified"]
                        }</dd>
                        
                        <dt class="col-sm-4">ETag:</dt>
                        <dd class="col-sm-8"><small><code>${
                          data.metadata.etag
                        }</code></small></dd>
                    </dl>
                `;

            document.getElementById("fileInfoContent").innerHTML = content;
            new bootstrap.Modal(document.getElementById("infoModal")).show();
          })
          .catch((error) => {
            alert("获取文件信息失败: " + error.message);
          });
      }

      // 删除文件
      function deleteFile(container, objectName) {
        if (!confirm(`确定要删除文件 "${objectName}" 吗？此操作不可恢复！`)) {
          return;
        }

        fetch(`/delete/${container}/${objectName}`, {
          method: "DELETE",
        })
          .then((response) => response.json())
          .then((data) => {
            if (data.error) {
              alert("删除失败: " + data.error);
            } else {
              alert("文件删除成功！");
              location.reload();
            }
          })
          .catch((error) => {
            alert("删除失败: " + error.message);
          });
      }

      // 格式化文件大小
      function formatBytes(bytes) {
        if (bytes === 0) return "0 B";
        const k = 1024;
        const sizes = ["B", "KB", "MB", "GB"];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
      }
    </script>
  </body>
</html>
